package com.effort.com.effort.excle.service;

import com.effort.com.effort.excle.core.util.ServerResponse;
import com.effort.com.effort.excle.pool.InfluxDbPool;
import com.effort.com.effort.excle.query.BaseQuery;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class QueryService {

    @Resource
    private InfluxDbPool influxDbPool;

    /**
     *  基础查询
     */
    public ServerResponse baseQuery(BaseQuery query) {

        Map<String,Object> map = new HashMap<>();

        // 查询具体数据
        InfluxDB influxdb =  influxDbPool.getConnectionByKey(query.getKey());


        String totalSql = getTotalSql(query);
        // 查询总记录条数
        QueryResult result = influxdb.query(new Query(totalSql, query.getDatabase()));
        // 获取真实的数量
        QueryResult.Result totalRes= result.getResults().get(0);
        List<List<Object>> values = totalRes.getSeries().get(0).getValues();
        long total = Double.valueOf(Double.parseDouble(values.get(0).get(1).toString())).longValue();

        String dataSql = getDataSql(query);
        result = influxdb.query(new Query(dataSql, query.getDatabase()));
        List<QueryResult.Series> series = result.getResults().get(0).getSeries();
        //
        List<List<Object>> datas = series.get(0).getValues();
        // 进行一个转换


        List<Map<String, Object>> res = datas.stream().map(item -> {
            Map<String, Object> temp = Maps.newHashMap();
            temp.put("value", item.get(1));
            try {
                temp.put("time", cn.hutool.core.date.DateUtil.format( new org.joda.time.DateTime(item.get(0).toString()).toDate(),"yyyy-MM-dd hh:mm:ss"));
            } catch (Exception e) {
                log.error("日期转换出现错误{}",e);
            }
            return temp;
        }).collect(Collectors.toList());
        map.put("data",res);
        map.put("total",total);
        return ServerResponse.ok(map);
    }

    private String getDataSql(BaseQuery query){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("select value from ")
                .append("\"")
                .append(query.getTagName())
                .append("\"")
                .append(" where time < '")
                .append(query.getEndDate())
                .append("'")
                .append(" and time > '")
                .append(query.getStartDate())
                .append("'")
                .append(" limit ")
                .append(query.getLimit())
                .append(" offset ")
                .append((query.getOffset()-1) * query.getLimit());
        return sqlBuilder.toString();
    }

    private String getTotalSql(BaseQuery query){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("select count(value) from ")
                .append("\"")
                .append(query.getTagName())
                .append("\"")
                .append(" where time < '")
                .append(query.getEndDate())
                .append("'")
                .append(" and time > '")
                .append(query.getStartDate())
                .append("'");
        return sqlBuilder.toString();
    }
}
